package com.suirich.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.suirich.common.Constants;
import com.suirich.utils.FileUtils;
import com.suirich.utils.ImageUtils;

@Controller
@RequestMapping("/upload")
public class UploadFileController {


    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(String filePath,int width,int height,
            @RequestParam("file") CommonsMultipartFile file,
            HttpServletRequest request, HttpServletResponse response) {

        String extName = FileUtils.getExtention(file.getOriginalFilename())
                .toLowerCase();

        String fileName = new Date().getTime() + extName;

        String photoPath = request.getSession().getServletContext()
                .getRealPath(filePath)
                + File.separator;

        String result = "";

        try {
            File photoFile = new File(photoPath);
            if (!photoFile.exists()) {
                photoFile.mkdirs();
            }
            File imageFile = new File(photoPath + fileName);
            file.transferTo(imageFile);

            String compressResult = ImageUtils.doCompress(imageFile, width, height, 1, false);
            
            if(StringUtils.isNotEmpty(compressResult)){
	            result = "{\"result\":\"" + Constants.SUCCESS_RESULT_FLAG
	                + "\",\"filePath\":\"" + filePath + "/" + fileName + "\"}";
            }else{
                result = "{\"result\":\"" + Constants.FAILURE_RESULT_FLAG + "\"}";
            }
        } catch (Exception e) {

            result = "{\"result\":\"" + Constants.FAILURE_RESULT_FLAG + "\"}";
        }

        try {
            response.getOutputStream().write(result.getBytes("utf-8"));
        } catch (Exception e) {
        }

        return null;
    }
}
